const mysql = require('mysql2/promise');
const config = require('../config/config');


function db() {
   return async function(ctx, next) {
        // create the connection to database
        if(!ctx.db) {
            const database = await mysql.createConnection({
                host: config.mysql.client.host,
                user: config.mysql.client.user,
                password: config.mysql.client.password,
                database: config.mysql.client.database,
                port: config.mysql.client.port
            });
            global.db = ctx.db = database;

            process.on('SIGTERM', function () {
                database.destroy();
           });
        }
    
        await next();
   }
}

module.exports = db;